﻿using Microsoft.Extensions.DependencyInjection;
using MyWeb.Common.Helper;
using MyWeb.Extensions.Redis;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyWeb.Extensions.ServiceExtensions.RedisCache
{
    /// <summary>
    /// Redis缓存 启动服务
    /// </summary>
    public static class RedisCacheSetup
    {
        /// <summary>
        /// Redis缓存 启动服务
        /// </summary>
        /// <param name="services"></param>
        /// <exception cref="ArgumentNullException"></exception>
        public static void AddRedisCacheSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            services.AddTransient<IRedisBasketRepository, RedisBasketRepository>();

            // 配置启动Redis服务，虽然可能影响项目启动速度，但是不能在运行的时候报错，所以是合理的
            services.AddSingleton<ConnectionMultiplexer>(sp =>
            {
                //获取连接字符串
                string? redisConfiguration = AppSettings.app(new string[] { "Redis", "ConnectionString" });
                if (!(redisConfiguration is null))
                {
                    var configuration = ConfigurationOptions.Parse(redisConfiguration, true);

                    configuration.ResolveDns = true;

                    return ConnectionMultiplexer.Connect(configuration);
                }
                throw new Exception("未获取到Redis连接字符串！");
            });

        }
    }
}
